package org.javaweb.cms_web.controller;

import org.javaweb.cms_web.model.Enum.UserStatus;
import org.javaweb.cms_web.model.User;
import org.javaweb.cms_web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class RetrievePasswordController {

    @Autowired
    private UserService userService;

    @GetMapping("/retrieve-password")
    public String retrievePassword() {
        return "retrievePassword";
    }

    @PostMapping("/retrieve-password")
    public String retrievePassword(@RequestParam String email,
                                   @RequestParam String password,
                                   @RequestParam String confirmPassword,
                                   @RequestParam String securityQuestion,
                                   @RequestParam String securityAnswer,
                                   Model model) {

        User user = userService.getUserByEmail(email);

        if (user == null) {
            model.addAttribute("error", "该邮箱未注册");
            return "retrievePassword";
        }

        if (user.getStatus() == UserStatus.TEAM_PENDING_REVIEW.getCode() || user.getStatus() == UserStatus.NOT_PASSED.getCode() || user.getStatus() == UserStatus.CANCELLED.getCode()){
            model.addAttribute("error", "该账号不可用");
            return "retrievePassword";
        }

        if (!password.equals(confirmPassword)) {
            model.addAttribute("error", "两次密码输入不一致");
            return "retrievePassword";
        }

        if (user.getPassword().equals(password)) {
            model.addAttribute("error", "新密码不能与老密码相同");
            return "retrievePassword";
        }

        if (!securityQuestion.equals(user.getSecurityQuestion())) {
            model.addAttribute("error", "密保问题错误");
            return "retrievePassword";
        }

        if (!securityAnswer.equals(user.getSecurityAnswer())) {
            model.addAttribute("error", "密保答案错误");
            return "retrievePassword";
        }

        user.setPassword(password);
        userService.updateUser(user);
        model.addAttribute("message", "重置密码成功");
        return "retrievePassword";
    }
}
